package com.kinoshita.manager.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kinoshita.common.jwt.JwtTokenUtil;
import com.kinoshita.manager.api.domain.UserLoginDO;
import com.kinoshita.manager.api.domain.UserLoginSuccessDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证请求入口
 */
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  @Autowired
  private ObjectMapper objectMapper;
  @Autowired
  private JwtTokenUtil jwtTokenUtil;

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response)
      throws AuthenticationException {
    // 从输入流中获取到登录的信息
    try {
      UserLoginDO userLoginDO = new ObjectMapper().readValue(request.getInputStream(), UserLoginDO.class);
      Authentication authenticate = getAuthenticationManager().authenticate(
          new UsernamePasswordAuthenticationToken(userLoginDO.getUsername(), userLoginDO.getPassword())
      );
      if (authenticate.isAuthenticated()) {
        //鉴权通过后获取到用户信息
        UserLoginSuccessDO userLoginSuccessDO = (UserLoginSuccessDO) authenticate.getPrincipal();
        //将用户信息通过JWT工具转为token
        String token = jwtTokenUtil.getJWT(userLoginSuccessDO.getId().toString(), userLoginSuccessDO.getUsername(), userLoginSuccessDO.getRoleCode());
        //将token放到用户信息中
        userLoginSuccessDO.setToken(token);
      }
      return authenticate;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  public ObjectMapper getObjectMapper() {
    return objectMapper;
  }

  public void setObjectMapper(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
  }
}
